package com.globallogic.vkulyk.SSHTool;

import static org.junit.Assert.*;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.jcraft.jsch.Session;

public class Unit_FilePutter extends SSHToolTester {
	private static final String FILE_NOT_FOUND_REMOTELY = "Output not equals, file not found remotely ";
	private String dstFile = "";
	private final ByteArrayOutputStream outActual = new ByteArrayOutputStream();

	@Before
	public void setup() {
		setVarsFromPropertiesFile("testData/testing.properties");
		String fileName = new File(srcFileForPut).getName();
		dstFile = dstDirForPut + "/" + fileName;
		new CommandExecutor(host, port, user, password, "rm -f " + dstFile)
				.execute();
		System.setOut(new PrintStream(outActual));
	}

	@Test
	public void shouldPutFile_whenCallExecute() {
		// given
		String outExpected = dstFile;

		new FilePutter(host, port, user, password, srcFileForPut, dstDirForPut)
				.execute();

		// when
		new CommandExecutor(host, port, user, password, "ls " + dstFile)
				.execute();
		String outActualWithRemovedNewLine = outActual.toString().replaceAll(
				"\\n", "");

		// then
		assertEquals(FILE_NOT_FOUND_REMOTELY, outExpected,
				outActualWithRemovedNewLine);
	}

	@Test
	public void shouldPutFile_whenCallExecuteInExistingSession() {
		// given
		ActionExecutor actionExecutor = new ActionExecutor(host, port, user,
				password);
		Session session = actionExecutor.openSession();
		String outExpected = dstFile;

		// when
		new FilePutter(host, port, user, password, srcFileForPut, dstDirForPut)
				.executeInExistingSession(session);
		
		// then
		new CommandExecutor(host, port, user, password, "ls " + dstFile)
				.executeInExistingSession(session);
		String outActualWithRemovedNewLine = outActual.toString().replaceAll(
				"\\n", "");
		assertEquals(FILE_NOT_FOUND_REMOTELY, outExpected,
				outActualWithRemovedNewLine);
		actionExecutor.closeSession(session);
	}

	@After
	public void cleanup() {
		System.setOut(null);
	}

}
